/**@FILE:UserServiceImpl.java
 * @AUTHOR:qingsheng.zheng
 * @DATE:2015-1-31 下午6:30:58*/
package com.xf.toy.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.xf.pub.exception.ServiceException;
import com.xf.pub.tool.StringUtils;
import com.xf.toy.bean.User;
import com.xf.toy.bean.UserExample;
import com.xf.toy.bean.UserExample.Criteria;
import com.xf.toy.dao.UserMapper;
import com.xf.toy.service.InviteCodeService;
import com.xf.toy.service.UserService;

/*******************************************
 * @COMPANY:alibaba
 * @CLASS:UserServiceImpl
 * @DESCRIPTION:
 * @AUTHOR:qingsheng.zheng
 * @VERSION:v1.0
 * @DATE:2015-1-31 下午6:30:58
 *******************************************/
@Service("userService")
public class UserServiceImpl implements UserService {
	@Resource
	private UserMapper userMapper;
	@Resource(name = "inviteCodeService")
	private InviteCodeService inviteCodeService;

	@Override
	public User selectUserDetail(Long userid) {
		return userMapper.selectByPrimaryKey(userid);
	}

	@Override
	public void registUser(User user) {
		userMapper.insert(user);
	}

	@Override
	public void updateUser(User user) {
		userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public void registUserWithInviteCode(User user, String inviteCode) {
		// if (StringUtils.isNull(inviteCode))
		// throw new ServiceException("");
		if (this.selectUserByOpenId(user.getOpenidWx()) != null)
			throw new ServiceException("");
		this.registUser(user);
		// inviteCodeService.invoke(inviteCode, user.getUserId());

	}

	public UserMapper getUserMapper() {
		return userMapper;
	}

	public InviteCodeService getInviteCodeService() {
		return inviteCodeService;
	}

	public void setInviteCodeService(InviteCodeService inviteCodeService) {
		this.inviteCodeService = inviteCodeService;
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	@Override
	public User selectUserByOpenId(String openId) {
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andOpenidWxEqualTo(openId);
		List<User> users = userMapper.selectByExample(example);
		if (users == null || users.isEmpty() || users.size() > 1)
			return null;
		return users.get(0);
	}

	@Override
	public User bindUser(String openid) {
		User user = this.selectUserByOpenId(openid);
		if (user == null) {
			user = new User();
			user.setCreatetime(new Date());
			user.setMoneyRemain(0D);
			user.setOpenidWx(openid);
			user.setUsername("");
			this.registUser(user);
			user = this.selectUserByOpenId(openid);
		}
		return user;

	}

}
